import pygame
import datamap
import copy
from level import *

def blend_range(image, begin, end, number):
    frame = []
    for i in xrange(0, number - 1): frame.append(copy.copy(image))
    step = ((end[0] - begin[0]) / (number - 1),
            (end[1] - begin[1]) / (number - 1),
            (end[2] - begin[2]) / (number - 1))
    for i in xrange(0, number - 1): 
        blend_color(frame[i], (begin[0] + step[0] * i, 
                               begin[1] + step[1] * i, 
                               begin[2] + step[2] * i))
    return frame

def blend_color(image, color):
    sf = pygame.Surface(image.get_rect().size)
    sf.fill(color)
    image.blit(sf, (0, 0), sf.get_rect(), pygame.BLEND_MULT)

def load_image(file, colorkey = None): # file exist
    image = pygame.image.load(file).convert()
    if colorkey: image.set_colorkey(colorkey, pygame.RLEACCEL)
    return image

def load_frame(file, (sx, sy), colorkey = None):
    image = pygame.image.load(file).convert()
    if colorkey is not None: image.set_colorkey(colorkey, pygame.RLEACCEL)
    allrect = image.get_rect()
    width = (allrect.width) // sx
    height = (allrect.height) // sy
    frame = []
    for y in range(0, allrect.height, height):
        for x in range(0, allrect.width, width):
            sub = pygame.Surface((width, height))
            sub.blit(image, (0, 0), (x, y, width, height))
            if colorkey: sub.set_colorkey(colorkey, pygame.RLEACCEL)
            frame.append(sub)
    return tuple(frame)

def node2pixel(node):
    return (node[0] * datamap.DataMap.GRID, node[1] * datamap.DataMap.GRID)
    
def pixel2node(pixel):
    return (int(pixel[0] // datamap.DataMap.GRID), int(pixel[1] // datamap.DataMap.GRID))

def mini_level(level, size):
    rawlvl = mapcfg[level]
    lvl = pygame.Surface((datamap.DataMap.XAXIS * datamap.DataMap.GRID, 
                          datamap.DataMap.YAXIS * datamap.DataMap.GRID))
    lvl.set_colorkey((0, 0, 0))
    lvl.fill((100, 100, 200))
    imgs = (None, None, None, # 0, 1, 2 
            load_image('res\\brick.bmp', (0, 0, 0)),
            load_frame('res\\base.bmp', (2, 1), (0, 0, 0))[0],
            load_image('res\\steel.bmp', (0, 0, 0)),
            load_image('res\\lawn.bmp', (0, 0, 0)),
            load_frame('res\\river.bmp', (2, 1), (0, 0, 0))[0],
            load_image('res\\ice.bmp', (0, 0, 0)),
            None)
    for item in rawlvl:
        if imgs[item[0]]:
            lvl.blit(imgs[item[0]], node2pixel(item[1]))
    lvl = pygame.transform.smoothscale(lvl, size)
    return lvl

def playsound(name, vol = 1):
    s = pygame.mixer.Sound('res\\%s.wav' % (name, ))
    s.set_volume(vol)
    s.play()


